<template>
  <el-main class="container">
    <el-container style="display: flex; justify-content: center; align-items: center; height: 100vh;">
      <el-card class="box-card" shadow="hover">
        <div class="clearfix">
          <h2>团队信息维护</h2>
        </div>
        <el-form ref="personForm" :model="form" class="person-form" label-position="top">
          <el-form-item label="队伍名称">
            <el-input v-model="form.teamName" placeholder="请输入队伍名称"></el-input>
          </el-form-item>
          <el-form-item label="队伍简称">
            <el-input v-model="form.teamAbbreviation" placeholder="请输入队伍简称"></el-input>
          </el-form-item>
          <el-form-item label="团队负责人(联系人)">
            <el-input v-model="form.teamLeader" placeholder="请输入负责人姓名"></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="form.phone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="详细地址">
            <el-input v-model="form.address" placeholder="请输入详细地址"></el-input>
          </el-form-item>
          <el-form-item label="责任书">
            <el-upload class="crad" :file-list="fileList" :http-request="customUpload" :on-preview="handlePreview"
              :on-remove="handleRemove" :before-remove="beforeRemove" list-type="picture-card"
              :on-success="uploadSuccess" :limit="2" :on-exceed="handleExceed" style="display: flex; flex-wrap: wrap;">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog v-model="dialogVisible" :title="dialogTitle">
              <img :src="dialogImageUrl" alt="预览图片" style="width: 90px">
            </el-dialog>
          </el-form-item>
          <div class="button-container-center">
            <el-form-item>
              <el-button type="primary" @click="saveData" class="button-save">保存并下一步</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-card>
    </el-container>
  </el-main>
</template>

<script setup>
import { useRouter } from 'vue-router'; // 引入路由
import { ref } from 'vue';
import axios from 'axios';

const router = useRouter();

const fileList = ref([]);

const form = ref({
  teamName: '',
  teamAbbreviation: '',
  address: '',
  teamLeader: '',
  phone: '',
  email: '',
  image: ''
});

// 对话框可见性
const dialogVisible = ref(false);
// 对话框标题
const dialogTitle = ref('图片预览');
// 对话框中显示的图片URL
const dialogImageUrl = ref('');

const token = localStorage.getItem('userToken');

// 图片地址，对话框中显示的图片URL
function handlePreview(file) {
  // 设置对话框标题和图片URL
  dialogTitle.value = file.name;
  dialogImageUrl.value = file.url;
  // 显示对话框
  dialogVisible.value = true;
}

//提交团队信息
async function saveData() {
  // 验证表单数据（手机号码的位数）
  if (!/^[1]\d{10}$/.test(form.value.phone)) {
    ElMessage.error('请输入正确的手机号');
    return;
  }
  // 验证表单数据（邮箱）
  if (!/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(form.value.email)) {
    ElMessage.error('请输入正确的邮箱地址');
    return;
  }
  // 验证表单数据（团队名称）
  if (!form.value.teamName || !form.value.teamAbbreviation || !form.value.teamLeader || !form.value.phone || !form.value.address || !form.value.image) {
    ElMessage.error('请填写完整信息');
    return;
  }
  try {
    const response = await axios.post('http://back1.idcfengye.com:15173/competition/teamgroup/add', form.value, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      }
    });

    // 处理后端响应
    if (response.status === 200 && response.data.success) {
      ElMessage.success('团队添加成功');
      router.push({ path: '/home/personnel' });
    } else if (response.status === 501) {
      ElMessage.error(response.data.msg);
    } else if (response.status === 502) {
      ElMessage.error('缺少权限');
    } else {
      ElMessage.error('添加团队失败');
    }
  } catch (error) {
    // 错误处理
    if (error.response) {
      // 请求已发出，但服务器响应的状态码不在 2xx 范围内
      if (error.response.status === 501) {
        ElMessage.error(error.response.data.msg);
      } else if (error.response.status === 502) {
        ElMessage.error('缺少权限');
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      ElMessage.error('请求超时，请检查网络连接');
    }
  }
}

// 上传文件
function customUpload(file) {
  const formData = new FormData();
  formData.append('file', file.file);

  const token = localStorage.getItem('userToken');
  const config = {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'multipart/form-data',
    },
  };

  axios.post('http://back1.idcfengye.com:15173/competition/upload', formData, config)
    .then(response => {
      const fileUrl = response.data.path;
      form.value.image = fileUrl; // 更新 form.image
      const uploadedFile = {
        name: file.file.name,
        url: fileUrl,
      };
      fileList.value.push(uploadedFile);
      ElMessage.success('文件上传成功');
    })
    .catch(error => {
      ElMessage.error('文件上传失败');
      console.error('Upload error:', error);
    });
}

// 移除文件
function handleRemove(file, fileList) {
  // 从fileList中移除文件
  const index = fileList.value.findIndex(f => f.name === file.name);
  if (index !== -1) {
    fileList.value.splice(index, 1);
  }
}
// 移除文件前的确认
function beforeRemove(file, fileList) {
  // 确认是否移除文件
  const confirmMessage = `确定要移除文件 ${file.name} 吗?`;
  if (window.confirm(confirmMessage)) {
    // 用户点击了确认，可以继续移除文件
    return true;
  } else {
    // 用户点击了取消，阻止文件移除
    return false;
  }
}
// 上传成功后的回调
function uploadSuccess(response, file, fileList) {
  // 上传成功后的回调
  console.log('Upload success:', response);
}
// 上传失败后的回调
function handleExceed(files, fileList) {
  ElMessage.warning(`最多只能上传两张照片`);
}
</script>


<style scoped>
::v-deep .el-upload--picture-card {
  --el-upload-picture-card-size: 90px;
}

::v-deep .el-upload-list--picture-card {
  --el-upload-list-picture-card-size: 90px;
}

.container {
  height: 1000px;
  /* 或您想要的高度 */
  display: flex;
  justify-content: center;
  align-items: center;
  /* padding: 20px; */
  box-sizing: border-box;
}

.form-container {
  width: 100%;
  max-width: 800px;
  /* 设置最大宽度 */
  display: flex;
  flex-direction: column;
  align-items: center;
}

.box-card {
  width: 600px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background-color: #a3c9c7;
  /* 调整为白色背景 */
  padding: 20px;
  border-radius: 8px;
}

.clearfix {
  margin-bottom: 20px;
  text-align: center;
}

.person-form {
  width: 100%;
  /* 确保表单宽度与容器一致 */
}

.button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.button-save {
  width: 450px;
  /* 根据需要调整按钮宽度 */
  margin: 0 10px;
  /* 给按钮之间添加间距 */
  background-color: black;
}

.button-container-center {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中（如果需要的话） */
  margin-top: 30px;
  /* 根据需要调整顶部间距 */
  width: 100%;
  /* 确保容器宽度 */
}
</style>
